package com.chcit.mobile.mvp.inventory.fragment.move;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;

import com.chcit.mobile.app.base.ScanToolQueryFragment;
import com.chcit.mobile.mvp.inventory.fragment.Stock.PackageQueryFragment;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chcit.custom.view.loader.QuickLoader;

import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.entity.Locator;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.inventory.adapter.MvPackageAdapter;
import com.chcit.mobile.mvp.inventory.contract.MovenPackageContract;
import com.chcit.mobile.mvp.inventory.di.component.DaggerMovenPackageComponent;
import com.chcit.mobile.mvp.inventory.presenter.MovenPakagePresenter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.xuexiang.xui.widget.spinner.editspinner.SimpleAdapter;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


import static com.jess.arms.utils.Preconditions.checkNotNull;


public class MovenPackageFragment extends ScanToolQueryFragment<MovenPakagePresenter> implements MovenPackageContract.View {


    @BindView(R.id.bt_mv_package_ok)
    Button btOk;
    @BindView(R.id.spinner_mv_package_locator)
    EditSpinner spinnerLocator;
    @BindView(R.id.rv_mv_package_list)
    RecyclerView mRecyclerView;
    MvPackageAdapter mAdapter;
    PackageBean packageBean;
    Locator locator;
    List<Locator> locators;
    boolean isRefresh;
    public static MovenPackageFragment newInstance( PackageBean packageBean) {
        MovenPackageFragment fragment = new MovenPackageFragment();
        fragment.packageBean = packageBean;
        return fragment;
    }
    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMovenPackageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }



    @Override
    protected int getLayoutId() {
        return R.layout.fragment_moven_pacakge;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        mCommonToolbar.setTitleText("包装移库");
        initRecyclerView();
        btQuery.setEnabled(false);
        vetPackageNo.addTextChangedListener(textWatcher);
        initSpinner();
        mCommonToolbar.getLeftMenuView(0)
                .setOnClickListener(v -> {
                    if(isRefresh) {
                        setFragmentResult(PackageQueryFragment.REFRESH_CODE, null);
                    }
                    pop();
                    if(getPreFragment() == null){
                        getActivity().finish();
                    }

                });
        mCommonToolbar.getRightMenuView(0).setEnabled(false);
        if(packageBean != null){

           onBarcodeEventSuccess(packageBean.getPackageNo());
        }
    }

    private void initSpinner() {
        JSONObject requestParam = new JSONObject();
        requestParam.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        mPresenter.getLocators(requestParam, list -> {
            locators = list;
            spinnerLocator.setItemData(locators);
            spinnerLocator.setIsFilterKey(true);
            spinnerLocator.getEditText().setTextSize(15);

            spinnerLocator.setImageOnClickListener(new View.OnClickListener() {
                int i = 0;
                @Override
                public void onClick(View v) {
                    if (i == 0) {
                        i++;
                    }
                }
            });
            spinnerLocator.setOnItemClickListener((parent, view, position, id)
                    -> locator = spinnerLocator.getSelectItem());



        });
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(spinnerLocator.getEditText().isFocused()){
            Locator scanLocator = new Locator();
            scanLocator.setName(barcodeData);
            int position = locators.indexOf(scanLocator);
           if(position >= 0){
               spinnerLocator.setText(barcodeData);
               locator = locators.get(position);
           }else {
               XToast.error(mContext,"系统没有该货位码，请联系管理员添加！").show();
               spinnerLocator.setText("");
           }
        }else{
            vetPackageNo.setText(barcodeData);
            btQuery.performClick();
        }
    }

    @OnClick({R.id.bt_common_query, R.id.bt_mv_package_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_common_query:
                JSONObject requestJson = new JSONObject();
                requestJson.put("packageNo",vetPackageNo.getText().toString());
                PackageBean packagebean = new PackageBean();
                packagebean.setPackageNo(vetPackageNo.getText().toString());
                int position = mAdapter.getData().indexOf(packagebean);
                if(position>= 0){
                    new MaterialDialog.Builder(mContext)
                            .title("提示")
                            .content("该包装号已被扫过，是否删除？")
                            .negativeText("删除")
                            .positiveText("取消")
                            .onNegative((dialog, which) -> {
                                mAdapter.remove(position);
                            })
                            .build()
                            .show();
                    return;
                }
                mPresenter.getPakcageInfo(requestJson, result -> {
                    if(result.size()>0){
                        if(result.get(0).getWarehouseId() != HttpClientHelper.getSelectWareHouse().getId()){
                            DialogUtil.showErrorDialog(mContext,"扫码失败，包装不在当前仓库:" +result.get(0).getPackageNo());
                            return;
                        }
                        mAdapter.addData(result);
                        btOk.setEnabled(true);
                        mCommonToolbar.getRightMenuView(0).setEnabled(false);
                    }
                });
                break;
            case R.id.bt_mv_package_ok:
                if(mAdapter.getData().size()>0){
                    if(locator == null){
                        XToast.warning(mContext,"移库货位不能为空").show();
                        return;
                    }
                    if(!locator.getName().equals(spinnerLocator.getText())){
                        XToast.warning(mContext,"请选择系统存在的货位！").show();
                        return;
                    }
                    List<String> packageNos = new ArrayList<>();
                    for(PackageBean p :mAdapter.getData()) {
                        packageNos.add(p.getPackageNo());
                    }

                   mPresenter.movePackage(locator.getId(),packageNos,()->{
                       showMessage("移库成功");
                       btOk.setEnabled(false);
                       mAdapter.getData().clear();
                       mAdapter.notifyDataSetChanged();
                       isRefresh = true;
                   });
                }
                break;
        }
    }

    private void initRecyclerView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter = new MvPackageAdapter(new ArrayList<>());
        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            //删除item
            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));

            }
        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        mAdapter.enableSwipeItem();
        mAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
        mAdapter.enableDragItem(mItemTouchHelper);
        mAdapter.setOnItemDragListener(listener);
        mRecyclerView.setAdapter(mAdapter);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        int mEditTextHaveInputCount = 0;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                if (mEditTextHaveInputCount == 0) {
                    btQuery.setEnabled(false);
                    if(mAdapter.getData().size()==0){
                        btOk.setEnabled(false);
                    }
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            //EditText最初内容为空 改变EditText内容时 个数加一
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                // 判断个数是否到达要求
                int EDITTEXT_AMOUNT = 1;

                if (mEditTextHaveInputCount >= EDITTEXT_AMOUNT) {
                    btQuery.setEnabled(true);
                    if(mAdapter.getData().size()>0){
                        mCommonToolbar.getRightMenuView(0).setEnabled(true);
                        btOk.setEnabled(true);
                    }
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    public boolean onBackPressedSupport() {
        mCommonToolbar.getLeftMenuView(0).performClick();
        return true;
    }
}
